package com.sg.business.permission.adapter;

import org.bson.types.ObjectId;
import org.eclipse.core.runtime.IAdapterFactory;

import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.sg.business.model.Document;
import com.sg.business.model.DocumentDefinition;
import com.sg.business.model.Folder;
import com.sg.business.model.FolderDefinition;
import com.sg.business.model.WorkDefinition;
import com.sg.business.permission.adapter.doc.DocumentACL;
import com.sg.business.permission.adapter.doc.FolderACL;
import com.sg.business.permission.adapter.docdef.DocumentDefACL;
import com.sg.business.permission.adapter.docdef.FolderDefACL;
import com.sg.business.permission.model.IACLControlable;

public class ACLAdapterFactory implements IAdapterFactory {

	@SuppressWarnings("rawtypes")
	@Override
	public Object getAdapter(Object adaptableObject, Class adapterType) {
		if (adapterType == IACLControlable.class) {
			if ((adaptableObject instanceof PrimaryObject)
					&& (Boolean.TRUE.equals(((PrimaryObject) adaptableObject)
							.getValue("skipPermission")))) {
				return null;
			}
			if (adaptableObject instanceof Document) {
				return new DocumentACL((Document) adaptableObject);
			} else if (adaptableObject instanceof Folder) {
				return new FolderACL((Folder) adaptableObject);
			} else if (adaptableObject instanceof DocumentDefinition) {
				DocumentDefinition dd = (DocumentDefinition) adaptableObject;
				ObjectId wdId = dd.getWorkDefinitionId();
				if(wdId == null) {
					return new DocumentDefACL(dd);
				}
				WorkDefinition workd = ModelService.createModelObject(
						WorkDefinition.class, wdId);
				int workdtype = workd.getWorkDefinitionType();
				if (WorkDefinition.WORK_TYPE_PROJECT == workdtype) {
					return new DocumentDefACL(dd);
				}
			} else if (adaptableObject instanceof FolderDefinition) {
				return new FolderDefACL((FolderDefinition) adaptableObject);
			}
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Class[] getAdapterList() {
		return new Class[] { IACLControlable.class };
	}

}
